<!--添加详情-->
<template>
  <div class="add-produce-data">
    <div class="top-bar-wrap">
      <div class="top-bar">
        <span class="iconfont backHistory" @click="spotCheckView" v-if="!$route.query.message">&#xe6eb;</span>
        <span class="title">{{ title }}</span>
        <span class="iconfont home" v-focusable @click="backToHomepage">&#xe668;</span>
      </div>
    </div>
    <div class="produce-content">
      <div class="add-part">
        <div class="add-list">
          <div class="add-item">
            <span class="label">部门：</span>
            <div class="box">
              <input readonly type="text" @click="selectDep" v-model="produceDataDetail.departmentName" placeholder="请选择部门" />
              <x-icon v-if="type === 'add'" type="ios-arrow-right" fill="#fff" size="24" @click="selectDep"></x-icon>
            </div>
          </div>
          <div class="add-item">
            <span class="label">数据时间：</span>
            <div class="box">
              <input readonly type="text" @click="selectTime" v-model="produceDataDetail.fillTime" placeholder="请选择日期" />
              <!-- <input readonly type="text" @click="selectJob" v-model="produceDataDetail.orgJobShiftName" placeholder="请选择班次"> -->
              <x-icon type="ios-arrow-right" fill="#fff" size="24" @click="selectTime"></x-icon>
            </div>
          </div>
          <div class="add-item">
            <span class="label">班次：</span>
            <div class="box">
              <!-- <input readonly type="text" @click="selectTime" v-model="produceDataDetail.fillTime" placeholder="请选择日期"> -->
              <input readonly type="text" @click="selectJob" v-model="produceDataDetail.orgJobShiftName" placeholder="请选择班次" />
              <!-- <span class="iconfont icon2" @click="selectJob">&#xe669;</span> -->
              <x-icon type="ios-arrow-right" fill="#fff" size="24" @click="selectJob"></x-icon>
            </div>
          </div>
          <div class="add-item">
            <span class="label">本班人员：</span>
            <span class="box">
              <div v-if="disabled">
                {{ produceDataDetail.members }}
              </div>
              <input class="full" v-else style="border-bottom: 1px solid #666;" maxlength="30" type="text" v-model="produceDataDetail.members" placeholder="请输入本班人员" />
            </span>
          </div>
          <div class="add-item">
            <span class="label">填报人：</span>
            <span class="box">{{ produceDataDetail.userName }}</span>
          </div>
          <div class="add-item" v-if="produceDataDetail.statusStr">
            <span class="label">状态：</span>
            <span class="status" :class="produceDataDetail.status == 1 ? 'draft' : 'submitted'">
              {{ produceDataDetail.statusStr }}
              <div class="reject-btn" v-if="produceDataDetail.status == 2 && !$route.query.message && privilege('wechat_produce', 'wechat_produce:reject')" @click="eventRejectpost">
                驳回
              </div>
            </span>
          </div>
          <div class="add-item" v-if="!isPeiyao">
            <span class="label">铁精粉产量/吨：</span>

            <span class="box">
              <div v-if="disabled">
                {{ produceDataDetail.output }}
              </div>
              <input class="full" v-else style="border-bottom: 1px solid #666;" maxlength="30" type="tel" v-model="produceDataDetail.output" />
            </span>
          </div>
        </div>
      </div>
      <div class="add-part">
        <add-data :disabled="disabled" :sectionList="produceDataDetail.sectionList"></add-data>
      </div>
    </div>
    <div class="fixed-bottom" v-if="!disabled">
      <div class="fixed-bottom-btns" v-if="auto === 1">
        <div class="btn" @click="handleAutoFill(0)">上 报</div>
      </div>
      <div class="fixed-bottom-btns" v-else>
        <div class="btn" @click="autoConfirm = true">自动填报</div>
        <div class="btn" @click="handleFinish(1)">保存</div>
        <div class="btn" @click="handleFinish(2)">提交</div>
      </div>
    </div>
    <div v-transfer-dom>
      <popup v-model="showDep">
        <!-- group already has a top border, so we need to hide header's bottom border-->
        <popup-header left-text="取消" right-text="确定" title="请选择部门" :show-bottom-border="false" @on-click-left="(showDep = false), (produceDataDetail.departmentId = '')" @on-click-right="eventDepChange"> </popup-header>
        <group gutter="0">
          <radio :options="depData" v-model="produceDataDetail.departmentId"></radio>
        </group>
      </popup>
    </div>
    <div v-transfer-dom>
      <popup v-model="showJob">
        <!-- group already has a top border, so we need to hide header's bottom border-->
        <popup-header left-text="取消" right-text="确定" title="请选择班次" :show-bottom-border="false" @on-click-left="(showJob = false), (produceDataDetail.orgJobShiftId = '')" @on-click-right="showJob = false"> </popup-header>
        <group gutter="0">
          <radio :options="jobList" v-model="produceDataDetail.orgJobShiftId"></radio>
        </group>
      </popup>
    </div>
    <div v-transfer-dom>
      <confirm v-model="showConfirm" title="提交确认" confirm-text="确认" cancel-text="取消" class="product-confirm" @on-cancel="onCancel" @on-confirm="onConfirm">
        <p style="text-align:center;">请检查是否正确，提交后不可更改，如需修改请联系上级</p>
        <table style="width: 100%" class="pro-table-chart" v-if="exceptionData.length" cellspacing="0" cellpadding="0" border="0">
          <thead>
            <tr>
              <th v-for="(item, index) in ['工艺', '数据项', '异常']" :key="index">
                {{ item }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in exceptionData.slice(0, 4)" :key="index">
              <td v-for="(ele, i) in item" :key="i">{{ ele }}</td>
            </tr>
            <tr v-if="exceptionData.length > 4">
              <td v-for="ele in 3" :key="ele">...</td>
            </tr>
          </tbody>
        </table>
      </confirm>
    </div>
    <div v-transfer-dom>
      <confirm v-model="rejectConfirm" title="确认驳回？" confirm-text="确认" cancel-text="取消" @on-cancel="rejectConfirm = false" @on-confirm="handleRejectpost">
        <p style="text-align:center;">驳回后当前数据会回到草稿状态重新修改。</p>
      </confirm>
    </div>
    <div v-transfer-dom>
      <confirm v-model="autoConfirm" title="提示" confirm-text="确认" cancel-text="取消" @on-cancel="autoConfirm = false" @on-confirm="handleAutoConfirm">
        <p style="text-align:center;">是否获取自动填报数据，获取到数据时会覆盖已填报数据项</p>
      </confirm>
    </div>
  </div>
</template>

<script>
import { PopupHeader, Popup, TransferDom, Group, Radio, Confirm } from 'vux';
import Organization from '@/components/common/replace/sellWorkOrderDepartment';
import addData from '@/components/common/produceData/addData';
import ProduceDataDao from '@/daos/produce_data_dao';
import { GetUser, Privilege } from '@/mixin';
export default {
  name: 'addProduceDetail',
  data() {
    return {
      showJob: false,
      showDep: false,
      jobList: [],
      depData: [],
      exceptionData: [],
      showConfirm: false,
      rejectConfirm: false,
      autoConfirm: false,
      params: {},
      timer: null,
      step: 0,
      dataForm: {
        departmentId: '',
        fillTime: '',
        departmentName: '',
        orgId: '',
        orgJobShiftId: '',
        orgJobShiftName: '',
        members: '',
        userName: '',
        userId: '',
        status: '',
        output: '',
        sectionList: [],
      },
      storeFrom: {},
    };
  },

  directives: {
    TransferDom,
  },
  mixins: [GetUser, Privilege],
  watch: {
    '$store.state.produceDataStatus'(value) {
      this.saveStore();
    },
    'produceDataDetail.orgJobShiftId'(value) {
      if (value) {
        this.jobList.forEach((item) => {
          if (Number(item.key) === Number(value)) {
            this.produceDataDetail.orgJobShiftName = item.value;
          }
        });
      } else {
        this.produceDataDetail.orgJobShiftName = '';
      }
    },
  },

  components: {
    Organization,
    PopupHeader,
    Popup,
    Group,
    Radio,
    addData,
    Confirm,
  },

  props: {
    title: {
      type: String,
      default: '添加生产数据',
    },
    //类型：add：添加；edit：编辑；see：查看此字段备用
    type: {
      type: String,
      default: 'add',
    },
    auto: {
      type: Number,
      default: 0,
    },
    produceDataDetail: {
      type: Object,
      default: () => {
        return {
          departmentId: '',
          fillTime: '',
          departmentName: '',
          orgId: '',
          orgJobShiftId: '',
          orgJobShiftName: '',
          members: '',
          userName: '',
          userId: '',
          status: '',
          output: '',
          sectionList: [],
          detailList: [],
        };
      },
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    userServiceAreaList() {
      if (this.$store.state.user) {
        let serviceAreaTree = this.$store.state.user.serviceAreaTree.children.map((e) => {
          return {
            key: e.id,
            value: e.departmentName,
          };
        });
        return serviceAreaTree;
      } else {
        return [];
      }
    },
    isPeiyao() {
      if (this.produceDataDetail.sectionList[0]) {
        return this.produceDataDetail.sectionList[0].name === '配药';
      }
      return false;
    },
  },
  inject: ['backToHomepage'],

  mounted() {
    if (!this.$store.state.user) {
      this.getUser();
    }
    this.getJobList();
    this.getFillDepartment();
  },
  methods: {
    getJobList() {
      ProduceDataDao.getJobList((res) => {
        res.forEach((item) => {
          this.jobList.push({ key: item.id, value: item.name });
        });
      });
    },
    getFillDepartment() {
      ProduceDataDao.getFillDepartment((res) => {
        this.depData = res.map((item) => ({
          key: item.departmentId,
          value: item.departmentName,
        }));
      });
    },
    spotCheckView() {
      // history.back(-1)
      if (this.type === 'see') {
        this.$router.go(-1);
        return;
      }
      this.$router.push('/produceData');
    },
    selectDep() {
      if (this.disabled || this.type !== 'add') {
        return;
      }
      this.showDep = true;
    },
    eventDepChange() {
      this.showDep = false;
      // this.getData();
      this.$emit('update', this.produceDataDetail.departmentId);
    },
    selectTime() {
      if (this.disabled) {
        return;
      }
      let that = this;
      this.$vux.datetime.show({
        cancelText: '取消',
        confirmText: '确定',
        format: 'YYYY-MM-DD',
        startDate: '',
        onConfirm(value) {
          // that.produceDataDetail.fillTime = value.replace(/-/g, '/')
          that.produceDataDetail.fillTime = value;
        },
        onHide(type) {
          if (type === 'cancel') {
          }
        },
      });
    },
    selectJob() {
      if (this.disabled) {
        return;
      }
      this.showJob = true;
    },
    eventRejectpost() {
      this.rejectConfirm = true;
    },
    handleRejectpost(id) {
      let data = {
        id: this.produceDataDetail.id,
      };
      ProduceDataDao.postDailyReportReject(data, (res) => {
        this.$vux.toast.show({ text: '驳回成功.' });
        this.$emit('update');
      });
    },
    handleAutoFill(tag = 0) {
      let text = '';
      if (!this.produceDataDetail.fillTime) {
        text = '请选择数据时间';
      } else if (!this.produceDataDetail.departmentId) {
        text = '请选择部门';
      } else if (!this.produceDataDetail.orgJobShiftId) {
        text = '请选择班次';
      }
      if (text) {
        this.$vux.toast.show({ text, type: 'warn' });
        return;
      }
      this.$emit('autofill', tag);
    },
    handleAutoConfirm() {
      this.handleAutoFill(1);
      // this.$emit('autofill', tag);
    },
    handleFinish(status, store = false) {
      let text = '';
      // console.log(status);
      if (!store && status === 2) {
        this.exceptionData.splice(0, this.exceptionData.length);
        this.$store.commit('changeProduceDataCheck');
      }
      this.produceDataDetail.sectionList.forEach((e) => {
        e.detailList.forEach((ele) => {
          ele.seriesParamsArray.forEach((element) => {
            if (element.statisticType) {
              this.$delete(element, 'inputDataExceptionDes');
              if (!this.isNumber(element.value)) {
                text = '请输入数字（小数点最多2位）';
              }
              // else if (Number.parseInt(element.value) > 99999) {
              //   text = "最多输入5个字符"
              // }
              else if (!store && element.inputDataType === 'number' && element.inputDataMaxValue && !this.maxCheck(element.value, element.inputDataMaxValue * 1.3)) {
                this.$set(element, 'inputDataExceptionDes', '超出最佳产量的30%');
                // element.inputDataExceptionDes = "超出最佳产量的30%"
                let sectionName = `${ele.processName}`;
                sectionName += /默认/.test(ele.processSectionSeriesName) ? '' : ` - ${ele.processSectionSeriesName}`;
                this.exceptionData.push({
                  sectionName,
                  seriesName: element.name,
                  dec: '超出最佳产量的30%',
                });
                // text = `${element.name}已超过最佳产能的30%`
              }
              // else if (!store && status === 2 && !element.value) {
              //   text = "请填写完整所有生产数据"
              // }
            }
          });
        });
      });

      if (text) {
        this.$vux.toast.show({ text, type: 'warn' });
        return;
      }

      this.params.fillTime = this.produceDataDetail.fillTime.replace(/\//g, '-');
      this.params.id = this.produceDataDetail.id;
      this.params.departmentName = this.produceDataDetail.departmentName;
      this.params.departmentId = this.produceDataDetail.departmentId;
      this.params.orgJobShiftId = this.produceDataDetail.orgJobShiftId;
      this.params.orgJobShiftName = this.produceDataDetail.orgJobShiftName;
      this.params.members = this.produceDataDetail.members;
      this.params.output = this.produceDataDetail.output;
      this.params.status = status;
      this.params.userId = this.produceDataDetail.userId;
      this.params.userName = this.produceDataDetail.userName;
      this.params.detailList = [];

      this.produceDataDetail.sectionList.forEach((item) => {
        item.detailList.forEach((sItem) => {
          sItem.data = JSON.stringify(sItem.seriesParamsArray);
        });
      });

      if (store) {
        this.handleSaveStore();
        return;
      }

      for (let i = 0; i < this.produceDataDetail.sectionList.length; i++) {
        for (let j = 0; j < this.produceDataDetail.sectionList[i].detailList.length; j++) {
          for (let k = 0; k < this.produceDataDetail.sectionList[i].detailList[j].parkingList.length; k++) {
            let item = this.produceDataDetail.sectionList[i].detailList[j].parkingList[k];
            if (this.produceDataDetail.status === 1) {
              if (!item.startTime && !item.endTime && !item.remark) {
                this.$vux.toast.show({ text: '停车时间、停车原因，必须有一个需要填写', type: 'warn' });
                return;
              }
            } else {
              if (!item.startTime || !item.endTime || !item.remark) {
                this.$vux.toast.show({ text: '停车时间、停车原因，请填写完整', type: 'warn' });
                return;
              }
            }
          }
        }
      }

      this.produceDataDetail.sectionList.forEach((item) => {
        item.sectionSeriesList = null;
        item.sectionFieldList = null;
        item.detailList.forEach((sItem) => {
          sItem.data = JSON.stringify(sItem.seriesParamsArray);
        });
        this.params.detailList.push(...item.detailList);
      });

      let item = this.params.detailList.find((e) => e.processName === '配药');
      if (item) {
        for (const series of item.seriesParamsArray) {
          if ((series.name === '加药时间' || series.name === '加药次数') && !series.value) {
            this.$vux.toast.show({ text: '加药时间、加药次数，请填写完整', type: 'warn' });
            return;
          }
          if (series.name === '加药时间' && series.value) {
            this.params.saveDrugTime = series.value.split(' , ');
          }
          if (series.name === '加药次数' && series.value) {
            this.params.saveDrugNum = series.value;
          }
          if (series.name === '报表通知' && series.value) {
            this.params.informConfigId = series.value;
          }
        }
      }

      if (status === 2) {
        this.showConfirm = true;
        return;
      }

      this.submit();
    },
    // 点击完成的时候，获取部门数据
    departmentSelected(params) {
      if (!!params.id) {
        // this.curDepartment = params;
        this.produceDataDetail.departmentId = params.id;
        this.produceDataDetail.departmentName = params.departmentName;
      } else {
        // this.departmentId = this.curDepartment.id;
      }
    },
    isNumber(source) {
      let flag = /^([0-9]*|\d*\.\d{1,2}?)$/.test(source);
      return flag;
    },
    maxCheck(source, max) {
      if (!source) {
        return true;
      }
      return +source <= +max;
    },
    saveStore() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(() => {
        let status = this.type === 'add' ? 2 : 1;
        this.handleFinish(status, true);
      }, 800);
    },
    handleSaveStore() {
      let key = this.type === 'add' ? 'addProduceData' : 'ProduceData' + this.produceDataDetail.id;
      localStorage.setItem(key, JSON.stringify(this.params));
    },
    submit() {
      this.$vux.loading.show({
        text: 'Loading',
      });
      ProduceDataDao[this.type === 'add' ? 'postProduceDetail' : 'putProduceDetail'](this.params, (res) => {
        this.$vux.loading.hide();
        if (this.params.status === 2) {
          this.$vux.toast.show({ text: '提交成功', type: 'success' });
        }
        if (this.params.status === 1) {
          this.$vux.toast.show({ text: '保存成功', type: 'success' });
        }
        setTimeout(() => {
          let key = this.type === 'add' ? 'addProduceData' : 'ProduceData' + this.produceDataDetail.id;
          localStorage.removeItem(key);
          this.$router.push({
            path: '/produceData',
          });
        }, 1200);
      });
      setTimeout(() => {
        this.$vux.loading.hide();
      }, 4000);
    },
    onCancel() {
      this.showConfirm = false;
    },
    onConfirm() {
      this.submit();
    },
  },
};
</script>
<style lang="less">
.product-confirm {
  color: #303133 !important;
  line-height: 1 !important;
  .weui-dialog__bd {
    color: #303133 !important;
    line-height: 1 !important;
  }
}
.pro-table-chart {
  color: #303133 !important;
  th {
    font-size: 14px;
    text-align: center;
    padding: 8px 0;
  }
  th:nth-child(4) {
    width: 150px;
  }
  td {
    font-size: 12px;
    text-align: center;
    box-sizing: border-box;
    padding: 8px 0;
    // border-bottom: 1px solid #ebeef5;
  }
  td,
  th {
    color: #303133 !important;
    line-height: 1 !important;
    text-overflow: inherit !important;
    word-wrap: normal !important;
    word-break: normal !important;
    white-space: normal !important;
    overflow: visible !important;
    border-right: 1px solid #c0c4cc;
  }
  td:nth-child(1),
  th:nth-child(1) {
    border-left: 1px solid #c0c4cc;
  }
  th {
    border-top: 1px solid #c0c4cc;
  }
  td,
  th {
    border-bottom: 1px solid #c0c4cc;
  }
}
</style>
<style lang="less" scoped>
.add-produce-data {
  .top-bar-wrap {
    height: 44px;
    color: #fff;
    position: fixed;
    width: 100%;
    left: 0px;
    top: 0px;
    background-color: #22233f;
    z-index: 10;
    .title {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 16px;
    }
    .backHistory {
      transform: rotate(90deg);
      -ms-transform: rotate(90deg); /* IE 9 */
      -moz-transform: rotate(90deg); /* Firefox */
      -webkit-transform: rotate(90deg); /* Safari 和 Chrome */
      -o-transform: rotate(90deg);
      line-height: 44px;
      font-size: 25px !important;
      margin-left: 10px;
    }
    .home {
      float: right;
      line-height: 44px;
      font-size: 17px;
      margin-right: 15px;
    }
  }
  .produce-content {
    padding: 64px 15px 60px;
    .add-part {
      padding-bottom: 10px;
      border-bottom: 1px solid #464656;
      &:last-child {
        border-bottom: 0;
      }
      .add-list {
        .add-item {
          display: flex;
          align-items: center;
          padding: 4px 0;
          overflow: hidden;
          // border-bottom: 1px solid #464656;

          .contentRight {
            position: relative;
            color: #fff;
            box-sizing: border-box;
            width: 65%;
            /deep/.header .header-content {
              justify-content: space-between;
            }

            .iu-select {
              text-align: right;
            }
            &.border {
              // border-bottom: 0.026667rem solid #464656;
              display: flex;
              justify-content: flex-end;
            }
            input {
              text-align: right;
              touch-action: none;
              width: 86%;
              border: 0;
              color: #ffffff;
              font-size: 16px;
              margin-right: 4px;
              &.full {
                width: 100%;
              }
            }
          }
          .label {
            width: 120px;
            font-size: 16px;
            color: hsla(0, 0%, 100%, 0.6);
          }
          .box {
            flex: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #ffffff;
            font-size: 16px;
            .iconfont {
              font-size: 12px;
            }
            input {
              touch-action: none;
              width: 60%;
              border: 0;
              color: #ffffff;
              font-size: 16px;
              &:readonly {
                background: none;
                color: #ffffff;
                // -webkit-text-fill-color:#ffffff;
              }
              &.full {
                width: 100%;
              }
            }
            input::-webkit-input-placeholder {
              /* Chrome/Opera/Safari */
              color: rgb(111, 111, 119) !important;
              font-size: 16px !important;
              text-align: left !important;
            }
            input::-moz-placeholder {
              /* Firefox 19+ */
              color: rgb(111, 111, 119) !important;
              font-size: 16px !important;
              text-align: left !important;
            }
            input:-ms-input-placeholder {
              /* IE 10+ */
              color: rgb(111, 111, 119) !important;
              font-size: 16px !important;
              text-align: left !important;
            }
            input:-moz-placeholder {
              /* Firefox 18- */
              color: rgb(111, 111, 119) !important;
              font-size: 16px !important;
              text-align: left !important;
            }
          }
          .status {
            display: flex;
            font-size: 16px;
            align-items: center;
            &.draft {
              color: #dd9710;
            }
            &.submitted {
              color: #456de6;
            }

            .reject-btn {
              color: #fff;
              font-size: 14px;
              background-color: #dd9710;
              padding: 2px 16px 4px;
              border-radius: 20px;
              margin-left: 8px;
              cursor: pointer;
            }
          }
        }
      }
    }
  }
}
.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 80px;
  background: #22233f;
  display: flex;
  align-items: center;
  .fixed-bottom-btns {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 20px;
    height: 40px;
    .btn {
      flex: 1;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #dd9710;
      color: #ffffff;
      font-size: 16px;
      border-radius: 20px;
      & + .btn {
        margin-left: 12px;
      }
      &:last-child {
        background: #2550d1;
      }
    }
  }
}
</style>
